package com.mapaoer.user.service.impl;

import com.mapaoer.user.entity.Permission;
import com.mapaoer.user.entity.Role;
import com.mapaoer.user.entity.User;
import com.mapaoer.user.repository.PermissionRepository;
import com.mapaoer.user.repository.RoleRepository;
import com.mapaoer.user.repository.UserRepository;
import com.mapaoer.user.service.RolePermissionService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class RolePermissionServiceImpl implements RolePermissionService {

    private final RoleRepository roleRepository;
    private final PermissionRepository permissionRepository;
    private final UserRepository userRepository;

    @Override
    @Transactional
    public Role createRole(String name, String description) {
        if (roleRepository.existsByName(name)) {
            throw new IllegalArgumentException("角色名称已存在: " + name);
        }
        Role role = new Role();
        role.setName(name);
        role.setDescription(description);
        return roleRepository.insert(role);
    }

    @Override
    @Transactional
    public Role assignPermissionsToRole(Long roleId, List<Long> permissionIds) {
        Role role = roleRepository.selectById(roleId);
        if (role == null) {
            throw new IllegalArgumentException("角色不存在: " + roleId);
        }

        Set<Permission> permissions = permissionIds.stream()
                .map(id -> {
                    Permission permission = permissionRepository.selectById(id);
                    if (permission == null) {
                        throw new IllegalArgumentException("权限不存在: " + id);
                    }
                    return permission;
                })
                .collect(Collectors.toSet());

        role.setPermissions(permissions);
        return roleRepository.save(role);
    }

    @Override
    @Transactional
    public void assignRolesToUser(Long userId, List<Long> roleIds) {
        User user = userRepository.selectById(userId);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在: " + userId);
        }

        Set<Role> roles = roleIds.stream()
                .map(id -> {
                    Role role = roleRepository.selectById(id);
                    if (role == null) {
                        throw new IllegalArgumentException("角色不存在: " + id);
                    }
                    return role;
                })
                .collect(Collectors.toSet());

        user.setRoles(roles);
        userRepository.save(user);
    }

    @Override
    @Transactional
    public Permission createPermission(String name, String description, String permissionKey) {
        if (permissionRepository.existsByPermissionKey(permissionKey)) {
            throw new IllegalArgumentException("权限标识已存在: " + permissionKey);
        }
        Permission permission = new Permission();
        permission.setName(name);
        permission.setDescription(description);
        permission.setPermissionKey(permissionKey);
        return permissionRepository.save(permission);
    }

    @Override
    public List<Role> getAllRoles() {
        return roleRepository.findAll();
    }

    @Override
    public List<Permission> getAllPermissions() {
        return permissionRepository.findAll();
    }

    @Override
    public List<Role> getUserRoles(Long userId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new IllegalArgumentException("用户不存在: " + userId));
        return user.getRoles().stream().collect(Collectors.toList());
    }
}